<?php
/**
 * Redis操作扩展类
 * ver 1.0
 * author Myxf
 */
class DbRedis{
    public $ver = "1.0";
    private $redis = null;

    function __construct($ip = "",$port = "",$key = "",$db = 0){
        if (empty($ip)) return;
        if (!class_exists('Redis'))exit("未安装Redis扩展！");
        $redis = new Redis();
        $redis->connect($ip, $port);
        $redis->auth($key);
        $redis->select(intval($db));
        if (!$redis) exit("Redis连接失败！");
        $this->redis = $redis;
    }

    /**
     * 获取一条数据
     * @access public
     * @param string $keys key值
     * @return string $ret 返回value
     */
    function getOne($key){
        $ret = $this->redis->get($key);
        return $ret;
    }

    /**
     * 获取多条数据
     * @access public
     * @param string $keys key值，参数为*时返回全部也可key*，也可以使用,分割返回多个，例如key1,key2
     * @return array $ret 返回value
     */
    function getAll($keys = "*"){
      $_ret = array();
      if (strpos($keys, "*")!==false){
        $ret = $this->redis->keys($keys);
        foreach ($ret as $key => $one) {
          $_ret[$key]['key'] = $one;
          $_ret[$key]['value'] = $this->getOne($one);
        }
        $ret = $_ret;
      }else{
        $keys = explode(",", $keys);
        $ret = $this->redis->mget($keys);
        foreach ($ret as $key => $one) {
          $_ret[$key]['key'] = $keys[$key];
          $_ret[$key]['value'] = $one;
        }
        $ret = $_ret;
      }
        return $ret;
    }

    /**
     * 添加一条数据
     * @access public
     * @param string $keys key
     * @param string $value 值
     */
    function add($key,$value){
        $this->redis->set($key, $value);
    }

    /**
     * 修改一条数据
     * @access public
     * @param string $keys key
     * @param string $value 值
     * @param boolean $ret 返回结果
     */
    function edit($key,$value){
        $ret = $this->redis->getSet($key, $value);
        return $ret;
    }

    /**
     * 删除一条数据
     * @access public
     * @param string $keys key，默认*删除全面或key*，可以指定一条例如key1
     * @param boolean $ret 返回结果
     */
    function del($key = "*"){
      $ret = $this->redis->del($key);
        return $ret;
    }

    /**
     * key是否存在
     * @access public
     * @param string $keys key
     * @param boolean $ret 返回结果
     */
    function exists($key){
      $ret = $this->redis->exists($key);
      return $ret;
    }

    /**
     * 设置存活时间，到期自动删除
     * @access public
     * @param string $keys key
     * @param string $time 过期时间，单位秒
     * @param boolean $ret 返回结果
     */
    function expire($key,$time){
      $ret = $this->redis->expire($key,$time);
      return $ret;
    }
}